package com.kevis.zhunblog.admin.customHtmlTag;

import com.kevis.zhunblog.admin.security.entity.SecurityUser;
import com.kevis.zhunblog.core.entities.PowerMenuEntity;
import com.kevis.zhunblog.service.PowerMenuService;
import com.kevis.zhunblog.service.RolePowerService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.Set;

public class CustomSecurityAction extends AbstractElementTagProcessor {
    public CustomSecurityAction(TemplateMode templateMode, String dialectPrefix, String elementName, boolean prefixElementName, String attributeName, boolean prefixAttributeName, int precedence) {
        super(templateMode, dialectPrefix, elementName, prefixElementName, attributeName, prefixAttributeName, precedence);
    }

    //@Autowired
    //private RolePowerMapper rolePowerMapper;
    private RolePowerService rolePowerService;
    private PowerMenuService powerMenuService;

    private static final String TAG_NAME = "roleAction";
    private static final int PRECEDENCE = 10000;

    public CustomSecurityAction(String dialectPrefix
//            , RedisTemplate redisTemplate
            , RolePowerService rolePowerService
            , PowerMenuService powerMenuService

    ) {
        super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PRECEDENCE);
        this.rolePowerService = rolePowerService;
        this.powerMenuService = powerMenuService;
    }


    @Override
    protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, IElementTagStructureHandler iElementTagStructureHandler) {
        /**
         * 1.根据url和menuCode 查询是否有这个菜单。 没有则返回空字符串
         * 2.根据url和menuCode 查询这个菜单有哪些角色。没有则返回空字符串。
         * 3.比较菜单角色与当前角色。不匹配则返回空字符串。超管9999除外
         * 4.匹配则创建html
         */
        IModelFactory modelFactory = iTemplateContext.getModelFactory();
        IModel model = modelFactory.createModel();

        StringBuilder html = new StringBuilder();
        String actionGuid = iProcessableElementTag.getAttributeValue("actionGuid");
        String actionName = iProcessableElementTag.getAttributeValue("actionName");
        String servletPath = ((WebEngineContext) iTemplateContext).getRequest().getServletPath();
        servletPath = servletPath.replaceAll("'", "").substring(1);

        //PowerMenuEntity powerMenuEntityParent = powerMenuService.getByListUrlAndMenuCode(servletPath);

        //PowerMenuEntity powerMenuEntity = powerMenuService.getByListUrlAndMenuCode(servletPath, actionName);
        PowerMenuEntity powerMenuEntity = powerMenuService.getByMenuCode(actionGuid, actionName);
        if (null == powerMenuEntity || powerMenuEntity.getId() == 0) {
            model.add(modelFactory.createText(html));
            // 利用引擎替换整合标签
            iElementTagStructureHandler.replaceWith(model, false);
            return;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof SecurityUser) {
            SecurityUser user = (SecurityUser) principal;
            String name = user.getUsername();
            //通过用户名查询所属角色
            int roleId = user.getRoleId();//如果要实时的角色信息，那就这边再去数据库查询一下用户最新的角色id
            if (roleId != 9999) {
                //通过url及传入的 menucode 查询指定的功能按钮对应的角色
                //Set<Integer> list = rolePowerService.getRolesByUrlMenuCode(servletPath, actionName);
                Set<Integer> list = rolePowerService.getRoleByPowerId(powerMenuEntity.getId());
                //二者角色比较
                if (list == null || list.size() == 0 || !list.contains(roleId)) {
                    model.add(modelFactory.createText(html));
                    // 利用引擎替换整合标签
                    iElementTagStructureHandler.replaceWith(model, false);
                    return;
                }
            }

            //有，则构建按钮的html
            String isPlain = iProcessableElementTag.getAttributeValue("isPlain");
            if (!StringUtils.hasLength(isPlain)) {
                isPlain = "false";
            }
            String dataOptions = iProcessableElementTag.getAttributeValue("dataOptions");
            if (!StringUtils.hasLength(dataOptions)) {
                dataOptions = "";
            }
            //有这个按钮权限，开始构建按钮文本
            html.append("<a");
            html.append(" href=\"javascript:void(0);\"");
            html.append(" class=\"easyui-linkbutton\"");
            html.append(String.format(" data-options=\"iconCls:'%s',plain:%s%s\" "
                    , powerMenuEntity.getIcon(), isPlain, dataOptions));
            html.append(String.format(" onclick=\"%s('%s')\" >", powerMenuEntity.getMenuCode(), powerMenuEntity.getGuid()));
            html.append(powerMenuEntity.getTitle());
            html.append("</a>");
        }
        model.add(modelFactory.createText(html));
        // 利用引擎替换整合标签
        iElementTagStructureHandler.replaceWith(model, false);
    }
}
